// 当前选择的目录句柄
let directoryHandle = null;
// 当前选择的文件句柄
let fileHandle = null;
// 当前文件内容
let currentFileContent = "";
// 当前路径栈
let pathStack = [];
// 存储目录句柄的映射
let directoryHandles = {};

// 打开目录
async function openDirectory() {
  try {
    directoryHandle = await window.showDirectoryPicker();
    pathStack = [directoryHandle.name];
    directoryHandles["/"] = directoryHandle;
    await renderDirectoryTree(directoryHandle);
    updatePathDisplay();

    document.getElementById("contentArea").innerHTML = `
      <h3>${directoryHandle.name}</h3>
      <p>文件夹内容将在左侧显示</p>
    `;
  } catch (err) {
    if (err.name !== "AbortError") {
      console.error("Error accessing directory:", err);
      alert("无法访问目录: " + err.message);
    }
  }
}

// 渲染目录树
async function renderDirectoryTree(dirHandle) {
  const treeContainer = document.getElementById("treeItemsContainer");
  treeContainer.innerHTML = "";

  for await (const entry of dirHandle.values()) {
    const itemElement = document.createElement("div");
    itemElement.className = "tree-item";
    itemElement.classList.add(
      entry.kind === "directory" ? "folder-icon" : "file-icon"
    );
    itemElement.textContent = entry.name;
    itemElement.dataset.name = entry.name;

    itemElement.addEventListener("click", async () => {
      // 移除之前选中的样式
      document.querySelectorAll(".tree-item.selected").forEach((el) => {
        el.classList.remove("selected");
      });

      // 添加当前选中样式
      itemElement.classList.add("selected");

      if (entry.kind === "file") {
        await selectFile(entry);
      } else {
        await selectDirectory(entry);
      }
    });

    treeContainer.appendChild(itemElement);
  }
}

// 更新路径显示
function updatePathDisplay() {
  const currentPath = "/" + pathStack.join("/");
  document.getElementById("currentPath").value = currentPath;
}

// 路径输入框按键事件
function handlePathInputKeyPress(event) {
  if (event.key === "Enter") {
    navigateToPath(event.target.value);
  }
}

// 导航到指定路径
async function navigateToPath(path) {
  try {
    const pathParts = path.split("/").filter((p) => p);
    if (pathParts.length === 0) {
      // 根目录
      if (directoryHandles["/"]) {
        directoryHandle = directoryHandles["/"];
        pathStack = [];
        await renderDirectoryTree(directoryHandle);
        updatePathDisplay();
      } else {
        await openDirectory();
      }
    } else {
      // 需要重新选择目录
      await openDirectory();
    }
  } catch (err) {
    alert("无法导航到指定路径: " + err.message);
  }
}

// 选择文件
async function selectFile(selectedFileHandle) {
  try {
    fileHandle = selectedFileHandle;
    const file = await fileHandle.getFile();
    currentFileContent = await file.text();

    document.getElementById("contentArea").innerHTML = `
      <h3>${fileHandle.name}</h3>
      <textarea id="fileEditor">${currentFileContent}</textarea>
    `;
  } catch (err) {
    console.error("Error reading file:", err);
    alert("无法读取文件: " + err.message);
  }
}

// 选择目录
async function selectDirectory(dirHandle) {
  try {
    directoryHandle = dirHandle;
    pathStack.push(dirHandle.name);

    // 存储目录句柄
    const currentPath = "/" + pathStack.join("/");
    directoryHandles[currentPath] = dirHandle;

    await renderDirectoryTree(dirHandle);
    updatePathDisplay();
    document.getElementById("contentArea").innerHTML = `
      <h3>${dirHandle.name}</h3>
      <p>文件夹内容将在左侧显示</p>
    `;
  } catch (err) {
    console.error("Error selecting directory:", err);
    alert("无法选择目录: " + err.message);
  }
}

// 返回上一级目录
async function goUpDirectory() {
  if (pathStack.length <= 1) {
    // 已经在根目录
    return;
  }

  try {
    // 获取上一级路径
    pathStack.pop();
    const parentPath = "/" + pathStack.join("/");

    // 从缓存中获取父目录句柄
    if (directoryHandles[parentPath]) {
      directoryHandle = directoryHandles[parentPath];
      await renderDirectoryTree(directoryHandle);
      updatePathDisplay();
      document.getElementById("contentArea").innerHTML = `
        <h3>${directoryHandle.name}</h3>
        <p>文件夹内容将在左侧显示</p>
      `;
    } else {
      // 如果没有缓存，需要重新选择目录
      await openDirectory();
    }
  } catch (err) {
    console.error("Error going up directory:", err);
    alert("无法返回上一级: " + err.message);
  }
}

// 保存文件
async function saveFile() {
  if (!fileHandle) {
    alert("没有选择文件");
    return;
  }

  try {
    const writable = await fileHandle.createWritable();
    const newContent = document.getElementById("fileEditor").value;
    await writable.write(newContent);
    await writable.close();
    alert("文件保存成功");
  } catch (err) {
    console.error("Error saving file:", err);
    alert("保存文件失败: " + err.message);
  }
}

// 新建文件
async function createNewFile() {
  if (!directoryHandle) {
    alert("请先选择目录");
    return;
  }

  const fileName = prompt("请输入文件名:");
  if (fileName) {
    try {
      const newFileHandle = await directoryHandle.getFileHandle(fileName, {
        create: true,
      });
      const writable = await newFileHandle.createWritable();
      await writable.write("");
      await writable.close();

      fileHandle = newFileHandle;
      currentFileContent = "";

      document.getElementById("contentArea").innerHTML = `
        <h3>${fileName}</h3>
        <textarea id="fileEditor"></textarea>
      `;

      await renderDirectoryTree(directoryHandle);
    } catch (err) {
      console.error("Error creating file:", err);
      alert("创建文件失败: " + err.message);
    }
  }
}

// 新建文件夹
async function createNewFolder() {
  if (!directoryHandle) {
    alert("请先选择目录");
    return;
  }

  const folderName = prompt("请输入文件夹名:");
  if (folderName) {
    try {
      await directoryHandle.getDirectoryHandle(folderName, {
        create: true,
      });
      await renderDirectoryTree(directoryHandle);
    } catch (err) {
      console.error("Error creating folder:", err);
      alert("创建文件夹失败: " + err.message);
    }
  }
}

// 删除选中项
async function deleteSelected() {
  if (!directoryHandle || !fileHandle) {
    alert("请先选择文件或目录");
    return;
  }

  if (confirm("确定要删除选中的项目吗？")) {
    try {
      await directoryHandle.removeEntry(fileHandle.name);
      await renderDirectoryTree(directoryHandle);
      document.getElementById("contentArea").innerHTML =
        "<p>请从左侧选择文件或文件夹</p>";
      fileHandle = null;
    } catch (err) {
      console.error("Error deleting item:", err);
      alert("删除失败: " + err.message);
    }
  }
}
